package cn.edu.ccut.refactor;

import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;

/**
 * 
 * @author Bai Yucheng 2008-1-21
 * 
 */
public class MoveSaturnAction extends SelectionDispatchAction {
	private ISelection selection;
	public static String folderName = "";  //$NON-NLS-1$

	public MoveSaturnAction(IWorkbenchSite site) {
		super(site);
		setText(Messages.getString("MoveSaturnAction.1"));  //$NON-NLS-1$
		this.selection = getSelection();
	}
	public void setIstructuredselection(
			IStructuredSelection istructuredselection) {
		this.selection = istructuredselection;
	}
	public void run() {
		if (!RefactorUtil.saveAll())
			return;
		if (selection instanceof StructuredSelection) {
			Object obj = ((StructuredSelection) selection).getFirstElement();
			if (obj instanceof IFile) {
				IFile file = (IFile) obj;
				folderName = file.getParent().getName();
				RenameSaturnFileProcessor renameunitprocessor = new RenameSaturnFileProcessor(file,(StructuredSelection) selection);
				RenameRefactoring renamerefactoring = new RenameRefactoring(renameunitprocessor);
				MoveRefactoringWizard moverefactoringwizard = new MoveRefactoringWizard(
						renamerefactoring, 8);
//				moverefactoringwizard.setCurrentProject(file.getProject());
				RefactoringWizardOpenOperation refactoringwizardopenoperation = new RefactoringWizardOpenOperation(
						moverefactoringwizard);
				try {
					RefactorUtil.deleteResourceMark(file);
					refactoringwizardopenoperation.run(PlatformUI.getWorkbench()
							.getActiveWorkbenchWindow().getShell(),
							Messages.getString("MoveSaturnAction.2"));  //$NON-NLS-1$
				} catch (Exception _ex) {
					_ex.printStackTrace();
				} 
			}
		
		}
	}
	
	public void selectionChanged(SelectionChangedEvent event) {
		this.selection = event.getSelection();
		setEnabled(computeEnabledState());
	}

	/*
	 * @see SelectionDispatchAction#update(ISelection)
	 */
	public void update(ISelection selection) {
		setEnabled(computeEnabledState());
	}

	private boolean computeEnabledState() {
		if (selection != null) {
			return true;
		} else {
			return false;
		}
	}

}
